package com.cxh.mediasessiondemo.classic_sample;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.cxh.mediasessiondemo.ICallback;
import com.cxh.mediasessiondemo.IController;

/**
 * Created by Cxh
 * Time : 2021/10/31  02:22
 * Desc : 继承自Activity/Fragment的UI组件，作为UI控制端，此处用fragment举例
 */
public class SampleMusicUI extends Fragment {

    private ServiceConnection mServiceConnection;
    private IController mController;
    private Context mContext;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // 连接成功拿到Service端的Binder代理, 就可以调用Service端远程方法了
                mController = IController.Stub.asInterface(service);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                mController = null;
            }
        };

        Intent intent = new Intent(context, SampleMusicService.class);
        context.bindService(intent, mServiceConnection, 0);
    }

    @Override
    public void onDetach() {
        mContext.unbindService(mServiceConnection);
        super.onDetach();
    }

    public void onClick() throws RemoteException {
        // 调用远程方法play()
        mController.play();
    }

    private ICallback.Stub mCallbackBinder = new ICallback.Stub() {
        @Override
        public void onSomethingChanged(int changeType) throws RemoteException {
            // 接受Service端的信息，更新UI
        }
    };
}
